package com.team7.happycommunity.personcentor.service.impl;

import com.github.pagehelper.PageException;
import com.team7.happycommunity.personcentor.entity.Dynamic;
import com.team7.happycommunity.personcentor.entity.MyPublishAcitivity;
import com.team7.happycommunity.personcentor.entity.PersonUser;
import com.team7.happycommunity.personcentor.dao.PersonUserDao;
import com.team7.happycommunity.personcentor.exception.LoginException;
import com.team7.happycommunity.personcentor.exception.MailboxStatusException;
import com.team7.happycommunity.personcentor.exception.RegisterException;
import com.team7.happycommunity.personcentor.exception.UpdatePasswordException;
import com.team7.happycommunity.personcentor.service.PersonUserService;
import com.team7.happycommunity.personcentor.util.MailUtils;
import com.team7.happycommunity.personcentor.util.Md5Util;
import javafx.fxml.LoadException;
import org.apache.http.HttpResponse;
import org.mortbay.util.ajax.JSON;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * (PersonUser)表服务实现类
 *
 * @author makejava
 * @since 2020-03-20 19:21:36
 */
@Service("personUserService")
public class PersonUserServiceImpl implements PersonUserService {
    @Value("${website}")
    private String website;
    @Value("${port}")
    private String port;
    @Resource
    private PersonUserDao personUserDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Resource
    private HttpServletResponse response;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public PersonUser queryById(Integer id) {
        return this.personUserDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<PersonUser> queryAllByLimit(int offset, int limit) {
        return this.personUserDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param personUser 实例对象
     * @return 实例对象
     */
    @Override
    public PersonUser insert(PersonUser personUser) {
        //进行密码加密
        //判断姓名，密码是否重复
        PersonUser user=new PersonUser();
        user.setName(personUser.getName());
        List<PersonUser> realPersonUsers = personUserDao.queryAll(user);
        if(realPersonUsers!=null&&realPersonUsers.size()>0){
            throw new RegisterException("姓名已存在");
        }
        PersonUser user2=new PersonUser();
        user2.setNickname(personUser.getNickname());
        List<PersonUser> personUsers2 = personUserDao.queryAll(user2);
        if(personUsers2!=null&&personUsers2.size()>0){
            throw new RegisterException("昵称已存在");
        }
        PersonUser user3=new PersonUser();
        user3.setMailbox(personUser.getMailbox());
        List<PersonUser> personUsers3 = personUserDao.queryAll(user3);
        if(personUsers3!=null&&personUsers3.size()>0){
            throw new RegisterException("邮箱已存在");
        }
        try {
            personUser.setPassword(Md5Util.encodeByMd5(personUser.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.personUserDao.insert(personUser);
        return personUser;
    }

    /**
     * 修改数据
     *
     * @param personUser 实例对象
     * @return 实例对象
     */
    @Override
    public PersonUser update(PersonUser personUser) {
        this.personUserDao.update(personUser);
        return this.queryById(personUser.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.personUserDao.deleteById(id) > 0;
    }

    @Override
    public boolean queryMailbox(String mailbox) {
        PersonUser user = personUserDao.queryByMailbox(mailbox);
        if(user==null||user.getMailboxStatus()!=0){
            if(user!=null&&user.getMailboxStatus()!=0){
                personUserDao.deleteByMailbox(mailbox);
            }
            return true;
        }
        return false;
    }
    @Override
    public void register(PersonUser user) {
        // 发送邮件，存储邮箱，并将mailbox_status状态改为1，并随机生成一个code邮箱令牌，并存储到数据库,密码加密
        //1.生成一个UUID数字
        String code = UUID.randomUUID().toString().replace("_","");
        user.setCode(code);
        String content="<a href='http://"+website+":"+port+"/personcentor/personUser/activate?code="+code+"'>点击激活</a>";
        MailUtils.sendMail(user.getMailbox(),content,"幸福小区邀请您注册，请点击链接");
        //2.进行密码加密
        try {
            String password = Md5Util.encodeByMd5(user.getPassword());
            user.setPassword(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //邮箱状态
        user.setMailboxStatus(1);
        //存储
        personUserDao.insert(user);
    }

    @Override
    public void updateMailboxStatus(String code) {
        PersonUser user=new PersonUser();
        user.setCode(code);
        List<PersonUser> personUsers = personUserDao.queryAll(user);
        if(personUsers==null||personUsers.size()==0){
            throw new MailboxStatusException("激活码不正确");
        }
        //1.修改邮箱状态
        personUserDao.updateMailboxStatusByCode(code,0);
    }

    @Override
    public PersonUser login(String text, String password) throws Exception {
        PersonUser user =null;
        if(text.contains("@")){
            //为邮箱
            user=personUserDao.queryByMailbox(text);
            if(user.getMailboxStatus()!=0){
                throw new LoginException("账号不存在");
            }


        }else{
            user=personUserDao.queryByPhoneNumer(text);
        }
        if(user == null){
            throw new LoginException("账号不存在");
        }

        String realPassword = Md5Util.encodeByMd5(password);
        if (!user.getPassword().equals(realPassword)){
            throw new LoginException("密码不存在");
        }
        //保存用户名到cookie和redis中，存活时间24小时，原理，客户端发送cookie过来，我取出来值name,看redis中是否有cookie的值，有则登录，
        //无，则提醒用户登录；
       // request.getSession();
        //Cookie c=new Cookie("name"+user.getName(),user.getName());
        //cookie存活时间24小时
        //c.setMaxAge(60*60*24);
       // c.setPath("/"); //根据个人的不用，在不同功能的路径下创建
       // response.addCookie(c);
        //存储到redis中，
        //2.将验证码保存到redis中
      //  redisTemplate.boundValueOps("name"+user.getName()).set(user.getName());
        //redisTemplate.boundValueOps("name"+user.getName()).expire(24, TimeUnit.HOURS);//24小时过期

        return user;
    }

    @Override
    public void phoneRegister(String cellPhNumber,String resetCode ) {
        //判断手机号是否被注册
        if(resetCode==null||!resetCode.equals("1")){
            PersonUser user = personUserDao.queryByPhoneNumer(cellPhNumber);
            if(user!=null){
                throw new RegisterException("手机号已经被注册");
            }
        }
        //1.生成一个六位验证码
        Random random=new Random();
        int code = random.nextInt(999999);
        if(code<100000){
            code=code+100000;
        }
        //2.将验证码保存到redis中
        redisTemplate.boundValueOps("code_"+cellPhNumber).set(code+"");
        redisTemplate.boundValueOps("code_"+cellPhNumber).expire(5, TimeUnit.MINUTES);//5分钟过期
        //3.将验证码发送到mq
        Map<String,String> map=new HashMap<>();
        map.put("phone",cellPhNumber);
        map.put("code",code+"");
        rabbitTemplate.convertAndSend("phone_code_exchange","phone."+cellPhNumber, map);
    }

    @Override
    public void codeCheck(String code, String phone) {
              //1.校验
        String sysCode = (String)redisTemplate.boundValueOps("code_" + phone).get();
        if(sysCode==null){
            throw new RegisterException("验证码过期或未发送");
        }
        if(!sysCode.equals(code)){
            throw new RegisterException("验证码不正确");
        }
    }

    @Override
    public void updatePasswordByCellPhNumber(String cellPhNumber, String password) throws Exception{
        personUserDao.updatePasswordByCellPhNumber(cellPhNumber,Md5Util.encodeByMd5(password));
    }

    @Override
    public PersonUser queryPersonInfoByName(String name) {

        return personUserDao.queryPersonInfoByName(name);
    }

    @Override
    public void updatePasswordBypassword(String name,String oldPassword, String password) throws Exception {
        //1.验证旧密码是否正确
        PersonUser user = personUserDao.queryPersonInfoByName(name);
       if(user.getPassword().equals(Md5Util.encodeByMd5(oldPassword))){
           //2.修改新密码
           personUserDao.updatePasswordByName( name,Md5Util.encodeByMd5(password));
       }else{
           throw new UpdatePasswordException("输入密码不正确");
       }

    }
    @Override
    public List<Dynamic> queryDynamicInfoByName(String name){
        return personUserDao.queryDynamicInfoByName(name);
    }

    @Override
    public  List<MyPublishAcitivity> queryMyPublishAcitivity(String name){
        return personUserDao.queryMyPublishAcitivity(name);
    }
    @Override
    public List<MyPublishAcitivity> queryJoinAcitivity(String name){
        return personUserDao.queryJoinAcitivity(name);
    }
    @Override
    public List<Dynamic> queryMyAttentionDynamicByName(String name){
        return personUserDao.queryMyAttentionDynamicByName(name);
    }
    @Override
    public void updateHeadImage(String userName, String imgurl){
        //查询用户的id
        PersonUser personUser=new PersonUser();
        personUser.setName(userName);
        List<PersonUser> personUsers = personUserDao.queryAll(personUser);

        personUserDao.updateHeadImage(personUsers.get(0).getId(),imgurl);
    }

}